package kr.hkit.xmlhandler.sax;

import java.io.File;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SAXEx {
	public static void main(String[] args) {
		SAXEx example = new SAXEx();
		try {
			example.parse();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void parse() throws Exception{
		File f= new File("personList.xml");
		
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser = factory.newSAXParser();
		SimpleHandler handler = new SimpleHandler();
		
		parser.parse(f, handler);
	}
	
	class SimpleHandler extends DefaultHandler{
		private final Logger logger = Logger.getLogger(SimpleHandler.class);

		@Override
		public void startDocument() throws SAXException {
			super.startDocument();
			logger.debug("startDocument() - Parsing Start");
		}
		
		@Override
		public void endDocument() throws SAXException {
			super.endDocument();
			logger.debug("endDocument() - Parsing End");
		}
		
		@Override
		public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
			super.startElement(uri, localName, qName, attributes);
			
			if (attributes.getLength()>0){
				logger.debug("startElement(String uri, String localName, String qName, Attributes attributes) - "+ uri +", "+localName+", "+qName+", "+attributes);
				for(int i=0; i<attributes.getLength(); i++){
					logger.debug("attributes - " + attributes.getQName(i) + " = " + attributes.getValue(i));
				}
			}else{
				logger.debug("startElement(String uri, String localName, String qName, Attributes attributes) - "+ uri +", "+localName+", "+qName+", attributes");
			}
		}

		@Override
		public void characters(char[] ch, int start, int length)throws SAXException {
			super.characters(ch, start, length);
			logger.debug("characters(char[] ch, int start, int length) - "+start+", "+length);
		}


		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			super.endElement(uri, localName, qName);
			logger.debug("endElement(String uri, String localName, String qName) - " + uri+", "+localName+", "+qName);
		}
		
		
	}
}
